package gat.common.util;

import com.bitsun.core.common.exception.AppException;
import com.bitsun.core.common.oss.Ossutil;
import gat.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author sxq
 * @date 2022/2/10
 */
@Slf4j
@Component
@RefreshScope
@EnableCaching
public class OssUtil {

    @Value("${oss.bucketName:}")
    private String bucketName;

    @Value("${oss.custome-domain:}")
    private String customeDomain;

    @Value("${spring.profiles.active:}")
    private String active;

    @Autowired
    private RedisService redisService;

    @Autowired
    private CosUtil cosUtil;

    private CosConfig getConfig() {
        return new CosConfig();
    }

/*    public String uploadFile(MultipartFile file) {
        String fileKey = "";
        try {
            String fileExtension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            fileKey = UUID.randomUUID() + fileExtension;
            Ossutil.uploadFile(bucketName, active.concat("/").concat(fileKey), file.getInputStream());
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new AppException("上传文件异常");
        }
        return customeDomain.concat("/").concat(active).concat("/").concat(fileKey);
    }*/

    public String uploadFile(MultipartFile file) {
        try {
            return cosUtil.uploadFile(file);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new AppException("上传文件异常");
        }
    }

    public String uploadFile(InputStream inputStream) {
        String fileKey = "";
        try {

            fileKey = UUID.randomUUID() + ".jpg";
            Ossutil.uploadFile(bucketName, active.concat("/").concat(fileKey), inputStream);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new AppException("上传文件异常");
        }
        return customeDomain.concat("/").concat(active).concat("/").concat(fileKey);
    }

}
